package dhy.com.tomcat.three.error;

import java.util.*;

/**
 * @author 大忽悠
 * @create 2022/3/10 21:12
 */
public class StringManager {

    private ResourceBundle bundle;

    /**
     * 设为private，单例模式的特点，要获取对象，可以通过getManager(String)方法
     */
    private StringManager() {
        bundle = ResourceBundle.getBundle("LocalStrings");
    }

    /**
     * StringManager类实例的包下properties文件中等号左边的值作为Key传递
     * 返回的是等号右面的信息
     */
    public String getString(String key) {
        if (key == null) {
            String msg = "key is null";

            throw new NullPointerException(msg);
        }
        String str = null;
        try {
            str = bundle.getString(key);
        } catch (MissingResourceException mre) {
            str = "Cannot find message associated with key '" + key + "'";
        }
        return str;
    }

    public String getString(String key,String ... args) {
        if (key == null) {
            String msg = "key is null";

            throw new NullPointerException(msg);
        }
        String str = null;
        try {
            str = bundle.getString(key);
            StringBuilder res=new StringBuilder();
            //将占位符{},换成传入的指令参数值
            String[] split = str.split("\\{}");
            for (int i = 0; i < split.length-1; i++) {
                res.append(split[i]).append(args[i]);
            }
            str=res.toString();
        } catch (MissingResourceException mre) {
            str = "Cannot find message associated with key '" + key + "'";
        }
        return str;
    }




    /**
     * 保存不同包下的StringManager对象---缓存
     */
    private static Hashtable managers = new Hashtable();

    /**
     * 单例模式用这个方法获取不同包的StringManager对象，
     * 因为可能同时被多个类使用产生错误，所以方法需要设置为同步
     */
    public synchronized static StringManager getManager(String packageName) {
        StringManager mgr = (StringManager) managers.get(packageName);
        if (mgr == null) {
            mgr = new StringManager();
            managers.put(packageName, mgr);
        }
        return mgr;
    }
}

